import 'dart:html';

import 'package:demo202112/utils/common_appbar.dart';
import 'package:flutter/material.dart';

/// @Author wywinstonwy
/// @Date 2022/1/27 8:36 上午
/// @Description: 
import 'package:event_bus/event_bus.dart';
// import 'package:logging/logging.dart';

int counterA = 1;
int counterB = 1;

//定义一个top-level（全局）变量，页面引入该文件后可以直接使用bus
var bus = EventBus();

class MyEventBus extends StatefulWidget {
  const MyEventBus({Key? key}) : super(key: key);

  @override
  _MyEventBusState createState() => _MyEventBusState();
}

class _MyEventBusState extends State<MyEventBus> {
  get eventBus => Event('123');


 @override
  void initState() {
    // TODO: implement initState
    super.initState();
    eventBus.on<UserLoggedInEvent>().listen((event) {
      // All events are of type UserLoggedInEvent (or subtypes of it).
      print(event.user);
    });
  }
  @override
  Widget build(BuildContext context) {
    bus.on("login", (arg) {
      // do something
    });
    return Scaffold(
      appBar: getAppBar('EventBus'),

    );
  }
}

class UserLoggedInEvent {
  String user;

  UserLoggedInEvent(this.user);
}

class NewOrderEvent {
  String order;

  NewOrderEvent(this.order);
}

//订阅者回调签名
typedef void EventCallback(arg);

class EventBus {
  //私有构造函数
  EventBus._internal();

  //保存单例
  static EventBus _singleton = EventBus._internal();

  //工厂构造函数
  factory EventBus()=> _singleton;

  //保存事件订阅者队列，key:事件名(id)，value: 对应事件的订阅者队列
  final _emap = Map<Object, List<EventCallback>?>();

  //添加订阅者
  void on(eventName, EventCallback f) {
    _emap[eventName] ??=  <EventCallback>[];
    _emap[eventName]!.add(f);
  }

  //移除订阅者
  void off(eventName, [EventCallback? f]) {
    var list = _emap[eventName];
    if (eventName == null || list == null) return;
    if (f == null) {
      _emap[eventName] = null;
    } else {
      list.remove(f);
    }
  }

  //触发事件，事件触发后该事件所有订阅者会被调用
  void emit(eventName, [arg]) {
    var list = _emap[eventName];
    if (list == null) return;
    int len = list.length - 1;
    //反向遍历，防止订阅者在回调中移除自身带来的下标错位
    for (var i = len; i > -1; --i) {
      list[i](arg);
    }
  }
}



